package org.javaboy.shiro.aspects;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.javaboy.shiro.anno.MyPerms;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@EnableAspectJAutoProxy
public class PermsAspect {

    @Pointcut("@annotation(org.javaboy.shiro.anno.MyPerms)")
    public void pc1() {

    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        //获取被拦截的方法
        Method method = signature.getMethod();
        //检查这个方法上有没有权限注解
        MyPerms myPerms = method.getAnnotation(MyPerms.class);
        if (myPerms == null) {
            //说明没有权限注解
            return pjp.proceed();
        }
        //执行当前方法所需要的权限
        String[] values = myPerms.value();
        Subject subject = SecurityUtils.getSubject();
        boolean[] permitted = subject.isPermitted(values);
        //如果多个权限只需要具备一个就可以访问
        for (boolean b : permitted) {
            if (b) {
                return pjp.proceed();
            }
        }
        return "unauthorized";
    }
}
